import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

const countSlice = createSlice({
    name: 'count',
    initialState: {
        num: 99
    },
    // 同步的程序员
    reducers: {
        addNum(state, { payload }) {
            state.num += payload
        },
        decNum(state, { payload }) {
            state.num -= payload
        }
    },
    // 专门用来处理异步actionCreator修改数据的操作
    extraReducers: (builder) => {
        builder
            .addCase(asyncAddNum.fulfilled, (state, { payload }) => {
                console.log('asyncAddNum.fulfillded : ', payload)
                state.num += payload
            })
            .addCase(asyncAddNum.rejected, (state, action)=>{
                console.log('asyncAddNum rejected',action.error.message)
            })
            .addCase(asyncAddNum.pending, (state, {payload})=>{
                console.log('asyncAddNum pending')
            })
    }
})

// 创建异步的actionCreator
export const asyncAddNum = createAsyncThunk('count/addNum', (payload) => {
    // 进行异步的操作
    // 异步的actionCreator的返回值是一个 promise对象
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            // 1. 成功的promise
            resolve(payload)
            // 2. 失败的promise
            // reject('error')
        },2000)
    })
})

// 同步的actionCreator
export const { addNum, decNum } = countSlice.actions

export default countSlice.reducer
